package com.foreveredu.propms.web.struts.action;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.propms.domain.Bill;
import com.foreveredu.propms.domain.ChargeItem;
import com.foreveredu.propms.domain.ChargeRecord;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.Owner;
import com.foreveredu.propms.domain.User;
import com.foreveredu.propms.service.IBusinessService;
import com.foreveredu.propms.service.IChargeService;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.HistoryDebtInputActionForm;
import com.foreveredu.propms.web.util.DigitalUpperCase;

/**
 * 处理业主历史债务输入请求
 * @author hushigang
 *
 */
public class HistoryDebtInputAction extends AbstractBaseDispatchAction {

	private IBusinessService businessService = null;
	private IManagementService managementService = null;
	private IChargeService chargeService = null;
	
	//获得日志记录器
	Logger log = Logger.getLogger(HistoryDebtInputAction.class);
	
	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public IBusinessService getBusinessService() {
		return businessService;
	}

	public void setBusinessService(IBusinessService businessService) {
		this.businessService = businessService;
	}

	public IChargeService getChargeService() {
		return chargeService;
	}

	public void setChargeService(IChargeService chargeService) {
		this.chargeService = chargeService;
	}

	// 跳转房产历史欠费信息输入页面
	public ActionForward input(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("input");
	}
	
	// 保存房产欠费信息，生成账单
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获得表单数据
		HistoryDebtInputActionForm hdiaf = (HistoryDebtInputActionForm)form;
		
		//欠费房产
		House house = managementService.findHouseByHouseId(hdiaf.getHouseId());
		if(house == null) {
			request.setAttribute("houseNotFoundError", "没有找到该房产信息！");
			return mapping.findForward("input");
		}
		//第1项金额表示物业服务费，第2项电费，第3项水费，第4项停车服务费、第5项垃圾清运费、第6项路灯电费、第7项二次提水电费
		float[] amounts = hdiaf.getAmount();
		
		//生成账单
		Bill bill = new Bill();
		bill.setHouse(house);
		
		//账单总金额
		float totalMoney = 0;
		
		//此账单所对应的收费记录集合
		Set<ChargeRecord> records = new HashSet<ChargeRecord>();
		for (int i = 0; i < amounts.length; i++) {
			if(amounts[i]!=0) {
				ChargeItem item = null;
				switch (i) {
				case 0:
					//第1项金额表示物业服务费
					item = chargeService.findChargeItemByItemId("1");
					break;
				case 1:
					//第2项金额表示电费
					item = chargeService.findChargeItemByItemId("3");
					break;	
				case 2:
					//第3项金额表示水费
					item = chargeService.findChargeItemByItemId("4");
					break;	
				case 3:
					//第4项金额表示停车服务费
					item = chargeService.findChargeItemByItemId("5");
					break;
				case 4:
					//第5项金额表示垃圾清运费
					item = chargeService.findChargeItemByItemId("6");
					break;
				case 5:
					//第6项金额表示路灯电费
					item = chargeService.findChargeItemByItemId("7");
					break;
				case 6:
					//第7项金额表示二次提水电费
					item = chargeService.findChargeItemByItemId("8");
					break;					
				}
				
				ChargeRecord cr = new ChargeRecord();
				cr.setChargeItem(item);
				cr.setBill(bill);
				cr.setWantMoney(amounts[i]);
				
				records.add(cr);
				chargeService.saveChargeRecord(cr);
				totalMoney += amounts[i];
			}
		}
		
		bill.setAmount(Float.parseFloat(new DecimalFormat("0.0").format(totalMoney)));
		bill.setRecords(records);
		bill.setYear(0);
		bill.setMonth(0);
		bill.setIsPaid(0);//设置账单为"未付款"状态
		bill.setIsInvoiced(0);//设置账单为"未开票"状态
		
		//创建该房产的每月账单
		businessService.saveBill(bill);
		
		request.setAttribute("house", house);
		request.setAttribute("owner", house.getOwner());
		
		return mapping.findForward("saveDone");
	}

	// 跳转房产历史欠费信息查询页面
	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("search");
	}
	
	// 显示房产历史欠费信息明细
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		//获得表单数据
		HistoryDebtInputActionForm hdiaf = (HistoryDebtInputActionForm)form;
		
		String houseId = hdiaf.getHouseId();
		String ownerName = hdiaf.getOwnerName();
		String phone = hdiaf.getPhone();
		String idCard = hdiaf.getIdCard();
		
		//获得该房产对象
		House house = null;
		if (houseId != null && !houseId.trim().equals("")) {
			house = managementService.findHouseByHouseId(houseId);
		} else if (ownerName != null && !ownerName.trim().equals("")) {
			Owner owner = managementService.findOwnerByName(ownerName);
			//如果业主拥有多处房产，该如何处理？
			house = (House)owner.getHouses().toArray()[0];
		} else if (phone != null && !phone.trim().equals("")) {
			Owner owner = managementService.findOwnerByPhone(phone);
			house = (House)owner.getHouses().toArray()[0];
		} else if (idCard != null && !idCard.trim().equals("")) {
			Owner owner = managementService.findOwnerByIdCard(idCard);
			house = (House)owner.getHouses().toArray()[0];
		}
	
		//判断是否从账单支付操作完毕之后跳转过来的
		House paidHouse = (House)request.getAttribute("paidHouse");
		int showSummary = 0;
		
		if(house== null && paidHouse != null) {
			house = paidHouse;
			showSummary = 1;
		}
		
		Bill historyBill = null;
		if (showSummary == 0) {
			//查询该房产的历史欠费信息(系统上线前)
			historyBill = businessService.findHistoryBillOfHouse(house);
			if (historyBill == null) {
				request.setAttribute("billNotFoundError", "没有找到该房产的历史欠费明细");
				return mapping.findForward("search");
			}
		} else {
			historyBill = businessService.findBillByHouseAndMonth(house, 0, 0);
		}

		request.setAttribute("bill", historyBill);
		request.setAttribute("amountUpperCase", DigitalUpperCase.toUpperCase(historyBill.getAmount()));
		request.setAttribute("house", house);
		request.setAttribute("showSummary", showSummary);
	
		if (showSummary == 1) {
			//历史欠款：
			float historyDebt = businessService.findHistoryDebtOfHouse(house);
			request.setAttribute("historyDebt", Float.parseFloat(new DecimalFormat("0.00").format(historyDebt)));
			
			//违约金： 
			//预缴金额：应缴金额：
			float paidAmount = ((Float)request.getAttribute("paidAmount")).floatValue();
			request.setAttribute("paidAmount", Float.parseFloat(new DecimalFormat("0.00").format(paidAmount)));
			
			//预存费用： 本次付费：
			float smallChange = ((Float)request.getAttribute("smallChange")).floatValue();
			request.setAttribute("smallChange", Float.parseFloat(new DecimalFormat("0.00").format(smallChange)));
			
			// 收费员	/抄表员 /开票员：当前登录用户
			User user = null;
			try {
				user = managementService.findUserByUsername(this.getPrincipal().getUsername());
			} catch(ClassCastException e) {
				//用户长时间不操作，session丢失后，跳转到登录页面
				return mapping.findForward("login");
			}
			request.setAttribute("nickname", user.getNickname());
			//开票日期：
			request.setAttribute("invoiceDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		}
		
		//获得该房产账单中的收费记录列表
		List<ChargeRecord> recordList = businessService.findChargeRecordsByBill(historyBill);
		request.setAttribute("recordList", recordList);
		
		//查询该房产的未付账单信息(系统上线后)
		
		return mapping.findForward("show");
	}
}
